

//////////////////////////////////////////////////////
//					_ooOoo_							//
//				   o8888888o						//
//				   88" . "88						//
//				   (| ^_^ |)						//
//				   O\  =  /O						//
//				____/`---'\____						//
//			  .'  \\|     |//  `.					//
//			 /  \\|||  :  |||//  \					//
//		    /  _||||| -:- |||||-  \					//
//		    |   | \\\  -  /// |   |					//
//			| \_|  ''\---/''  |   |					//
//			\  .-\__  `-`  ___/-. /					//
//		  ___`. .'  /--.--\  `. . ___				//
//		."" '<  `.___\_<|>_/___.'  >'"".			//
//	  | | :  `- \`.;`\ _ /`;.`/ - ` : | |			//
//	  \  \ `-.   \_ __\ /__ _/   .-` /  /           //
//========`-.____`-.___\_____/___.-`____.-'=========//
//				             `=---='                //
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^//
//      佛祖保佑       永无BUG       永不修改			//
//////////////////////////////////////////////////////



#import "ViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "AFNetworkTool.h"
#import "WXApi.h"

@interface ViewController ()<WXApiDelegate>
@property (strong, nonatomic) IBOutlet UIButton *alipayBtn;
@property (strong, nonatomic) IBOutlet UIButton *wechatpayBtn;
- (IBAction)selectAction:(UIButton *)sender;

- (IBAction)payAction:(UIButton *)sender;
@property (strong, nonatomic) IBOutlet UITextField *NumberTextField;

@end

@implementation ViewController
{
    // 记录支付类型，0支付宝，1微信
    NSInteger selection ;
    // 微信支付数据
    NSString *appId ;
    NSString *nonceStr ;
    NSString *package ;
    NSString *partnerId ;
    NSString *prepayId ;
    NSString *sign ;
    UInt32 timeStamp ;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    selection = 0 ;// 默认支付宝
}
- (IBAction)selectAction:(UIButton *)sender {
    if ( sender == self.alipayBtn ) {
        self.alipayBtn.backgroundColor = [UIColor redColor];
        self.wechatpayBtn.backgroundColor = [UIColor grayColor];
        selection = 0 ;
    }else if ( sender == self.wechatpayBtn){
        self.wechatpayBtn.backgroundColor = [UIColor redColor];
        self.alipayBtn.backgroundColor = [UIColor grayColor];
        selection = 1 ;
    }
}

- (IBAction)payAction:(UIButton *)sender {
    if (selection == 0 ) {
        
        /**
         *  支付宝加密需要在服务端处理，本地请求数据，然后再发给支付宝，调起支付
         */
        
        NSLog(@"支付宝支付") ;
        NSString *appScheme = @"wx51bcbabb782e9d12";
        
        // 此处向服务器请求支付需要的信息
        NSString *url = [NSString stringWithFormat:@"http://121.41.110.104:9082/mall/pay/alipay/getpaydata.html?userId=%@&token=%@&orderNumber=1444962847",@"1037",@"token"] ;
        [AFNetworkTool JSONDataWithUrl:url success:^(id json) {
            if ([json[@"code"] isEqual:@0 ]) {
                // 支付
                NSString *orderString = json[@"data"][@"alipaydata"] ;
                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                        NSString *result = resultDic[@"result"];
                        NSRange range = [result rangeOfString:@"success="];
                        
                        NSInteger index = range.location + range.length ;
                        
                        if ([[result substringWithRange:NSMakeRange(index+1, 4)] isEqualToString:@"true"]) {
                            [self alertViewWuthTitle:@"恭喜" Msg:@"支付成功啦！"] ;
                        }else {
                            [self alertViewWuthTitle:@"提示" Msg:@"支付失败" ] ;
                        }
                    }else {
                        [self alertViewWuthTitle:@"提示" Msg:@"支付失败" ] ;
                    }
                }];
            }
        } fail:^{
        }];
    }else if (selection == 1 ){
        NSLog(@"微信支付");
        // 判断是否安装微信
        if ([WXApi isWXAppInstalled]) {
            
            // 此处向服务器请求支付需要的信息
            NSString *url = [NSString stringWithFormat:@"http://121.41.110.104:9082/mall/pay/wxpay/getpaydata.html?userId=%@&token=%@&orderNumber=1444962847",@"1037",@"token"] ;
            NSLog(@"%@",url);
            /**
             *  我这里是给服务端发送订单号，返回订单信息，然后用订单信息调起微信支付
             *
             *  后台数据不一样可能有略微不同，自己具体分析处理吧
             */
            [AFNetworkTool JSONDataWithUrl:url success:^(id json) {
                NSLog(@"%@",json);
                if ([json[@"code"] isEqual:@0]) {
                    NSDictionary *dict = json[@"data"][@"wxpaydata"] ;
                    appId = dict[@"appId"];
                    nonceStr = dict[@"nonceStr"];
                    package = dict[@"package"];
                    partnerId = dict[@"partnerId"];
                    prepayId = dict[@"prepayId"];
                    sign = dict[@"sign"];
                    timeStamp = [dict[@"timeStamp"] intValue];
                    
                    if (prepayId.length == 0 ) {
                        [self alertViewWuthTitle:@"提示" Msg:@"此订单已经支付，请勿重复支付"] ;
                        return ;
                    }
                    /*   下面这些数据是必须的哈  */
                    PayReq* req  = [[PayReq alloc] init];
                    req.openID = appId ;
                    req.partnerId = partnerId ;
                    req.prepayId = prepayId ;
                    req.nonceStr = nonceStr ;
                    req.package = package ;
                    req.sign = sign ;
                    req.timeStamp = timeStamp ;
                    
                    [WXApi sendReq:req];
                }
            } fail:^{
            }];
        }else {
            [self alertViewWuthTitle:@"提示" Msg:@"尚未安装微信"];
        }
    }
}

- (void)alertViewWuthTitle: (NSString *)title Msg : (NSString *)message {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show ] ;
}

@end
